package cn.itcast.bos.web.action;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.bos.domain.page.PageBean;
import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.web.action.common.BaseAction;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Think on 2017/9/24.
 */
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope(value = "prototype")
public class PromotionAction extends BaseAction<Promotion> {

    // 获取商品详情列表
    @Action(value = "promotion_pageQuery", results = {@Result(name = "success", type = "json")})
    public String pageQuery() throws Exception {
        PageBean<Promotion> pageData = WebClient.create(Constants.BOS_MANAGEMENT_URL + "/services/promotionService/findPageData?page=" + page + "&rows=" + rows)
                .type(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .get(PageBean.class);
        // 返回json
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("totalCount", pageData.getTotalElements());// 总记录数
        map.put("pageData", pageData.getContent());
        ServletActionContext.getContext().getValueStack().push(map);
        return SUCCESS;
    }

    /**
     * 查看活动详情
     */
    @Action(value = "promotion_showDetail")
    public String showDetail() throws Exception {
        //先判断id,是否有对应的html,如果存在,直接返回
        //查看html存放的文件夹
        String realPath = ServletActionContext.getServletContext().getRealPath("/freemarker");
        File file = new File(realPath + "/" + model.getId() + ".html");
        //如果没有,查询数据库,结合freemarker模板生成页面
        if (!file.exists()) {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
            // 设置模板加载的路径
            configuration.setDirectoryForTemplateLoading(new File(ServletActionContext.getServletContext().getRealPath("/WEB-INF/template_freemarker")));
            // 通过设置的路径，查找ftl模板
            Template template = configuration.getTemplate("promotion.ftl");
            // 使用webservice的技术，使用ID获取当前ID的商品详情
            Promotion promotion = WebClient.create(Constants.BOS_MANAGEMENT_URL + "/services/promotionService/findById/" + model.getId())
                    .type(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .get(Promotion.class);
            //创建模板页面所需的数据模型
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("promotion", promotion);   //属性值对应模板页面所需的属性名
            // 合并输出，输出编码用UTF-8的形式
            template.process(dataModel, new OutputStreamWriter(new FileOutputStream(file)));
        }
        //如果文件存在,直接把文件返回,响应编码用UTF-8
        ServletActionContext.getResponse().setContentType("text/html;charset:utf-8");
        FileUtils.copyFile(file, ServletActionContext.getResponse().getOutputStream());
        return NONE;
    }
}
